# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2021/10/19 15:47
# @File           : view.py
# @IDE            : PyCharm
# @desc           : 接口文件
import datetime
import time
from typing import Optional
from fastapi import APIRouter, Depends, Query
from core.validator import vali_telephone
from utils.tools import get_code, calculate_time
from . import schemas, crud
from core.database import db_getter, AsyncSession, redis_getter, Redis
from utils.response import SuccessResponse

app = APIRouter()


###########################################################
#    客户管理
###########################################################
@app.get("/", summary="客户管理接口状态")
def app_root(version: str):
    data = {
        "当前时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "test": "客户管理",
        "version": version
    }
    return SuccessResponse(data=data)


@app.post("/manage/", summary="创建客户信息")
async def create_customer(data: schemas.CustomerIn, db: AsyncSession = Depends(db_getter)):
    return SuccessResponse(await crud.CustomerDal(db).create_data(data=data))


@app.get("/manage/", summary="获取客户列表")
async def get_customers(
        page: int = 1,
        limit: int = 10,
        db: AsyncSession = Depends(db_getter),
        grade: Optional[str] = Query(None, max_length=1, title="客户等级", regex="A|B|C", description="选择A或B或C"),
        platform: Optional[int] = Query(None, ge=0, le=4, title="平台", description="大于0，小于4"),
):
    datas = await crud.CustomerDal(db).get_datas(
        page=page,
        limit=limit,
        grade=grade,
        platform=platform
    )
    count = await crud.CustomerDal(db).get_count(grade=grade, platform=platform)
    return SuccessResponse(data=datas, count=count)


@app.delete("/manage/batch/", summary="删除客户列表")
async def delete_customers(data: schemas.CustomerDel, db: AsyncSession = Depends(db_getter)):
    return SuccessResponse(await crud.CustomerDal(db).delete_datas(data.ids))


@app.put("/manage/{data_id}/", summary="更新客户信息")
async def put_customers(data_id: int, data: schemas.CustomerIn, db: AsyncSession = Depends(db_getter)):
    return SuccessResponse(await crud.CustomerDal(db).put_data(data_id, data))


###########################################################
#    邀请码管理
###########################################################
@app.get("/invitation/code/", summary="获取邀请码")
async def get_invitation_code(telephone: str, rd: Redis = Depends(redis_getter)):
    telephone = vali_telephone(telephone)
    code = get_code(6, True)
    await rd.set(telephone, code, 60)
    result = {
        "code": code,
        "ex": calculate_time(seconds=60)
    }
    return SuccessResponse(result)


@app.post("/invitation/code/", summary="验证邀请码")
async def check_invitation_code(data: schemas.InvitationCodeCheck, rd: Redis = Depends(redis_getter)):
    value = await rd.get(data.telephone)
    if value == data.value:
        return SuccessResponse("验证成功")
    return SuccessResponse("验证失败")
